package cn.itsource.pethome.org.service.impl;

import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.org.domain.Employee;
import cn.itsource.pethome.org.mapper.EmployeeMapper;
import cn.itsource.pethome.org.service.IEmployeeService;
import cn.itsource.pethome.user.domain.Logininfo;
import cn.itsource.pethome.user.mapper.LogininfoMapper;
import cn.itsource.pethome.util.MD5Utils;
import cn.itsource.pethome.util.StrUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void insert(Employee employee) {
        employee.setPassword("111111");

        this.encryption(employee);//user  ox011
        // 7.1.3 将logininfo也保存一份
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setDisable(1);
        logininfo.setType(0);
        logininfoMapper.insert(logininfo);
        //保存logininfo信息
        employee.setLogininfo_id(logininfo.getId());
        super.insert(employee);
    }

    private void encryption(Employee employee) {
        String RandomString = StrUtils.getComplexRandomString(32);
        employee.setSalt(RandomString);//先不管
        String pwd = MD5Utils.encrypByMd5(employee.getPassword() + RandomString);
        employee.setPassword(pwd);
    }

    @Override
    public void update(Employee employee) {
        Employee user1 = super.queryOne(employee.getId());
        BeanUtils.copyProperties(employee,user1);
        super.update(user1);
        //因为修改的时候可能没有LogininfoId
        //从user表中去获取logininfo的id
        Long logininfoId = user1.getLogininfo_id();
        //去查询logininfo 的数据
        Logininfo logininfo = logininfoMapper.queryOne(logininfoId);
        //获取之前的id
        Long id = logininfo.getId();
        //将修改后的user复制给logininfo
        BeanUtils.copyProperties(user1,logininfo);
        //将之前的id设置回来
        logininfo.setId(id);
        //修改logininfo
        logininfoMapper.update(logininfo);
    }

    @Override
    public void delete(Long id) {
        Employee employee = super.queryOne(id);
        logininfoMapper.delete(employee.getDepartment_id());
        super.delete(id);
    }

    @Override
    public List<Employee> queryEmpByShopId(Long shopid) {
        return employeeMapper.queryEmpByShopId(shopid);
    }
}
